package com.ruoyi.web.controller.bussiness;

import java.io.*;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.domain.DragSysConfig;
import com.ruoyi.system.domain.MedicineDetail;
import com.ruoyi.system.service.IDragSysConfigService;
import com.ruoyi.system.service.IMedicineDetailService;
import com.ruoyi.web.controller.common.XunFeiUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.MedicineInfo;
import com.ruoyi.system.service.IMedicineInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * meidicineInfoController
 * 
 * @author ruoyi
 * @date 2024-12-17
 */
@RestController
@RequestMapping("/system/meidicineInfo")
public class MedicineInfoController extends BaseController
{
    @Autowired
    private IMedicineInfoService medicineInfoService;
    @Autowired
    private IDragSysConfigService dragSysConfigService;
    @Autowired
    private IMedicineDetailService medicineDetailService;
    private Object HttpClientUtil;


    /**
     * 查询meidicineInfo列表
     */
    @GetMapping("/list")
    public TableDataInfo list(MedicineInfo medicineInfo)
    {
        startPage();
        List<MedicineInfo> list = medicineInfoService.selectMedicineInfoList(medicineInfo);
        return getDataTable(list);
    }

    /**
     * 导出meidicineInfo列表
     */
    @Log(title = "meidicineInfo", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MedicineInfo medicineInfo)
    {
        if(medicineInfo.getIds()==null){
            throw new GlobalException("您未选择任何数据");
        }
        if(medicineInfo.getIds().length==0){
            throw new GlobalException("您未选择任何数据");
        }
        List<MedicineInfo> list = medicineInfoService.selectMedicineInfoByIds(medicineInfo.getIds());
        ExcelUtil<MedicineInfo> util = new ExcelUtil<MedicineInfo>(MedicineInfo.class);
        util.exportExcel(response, list, "meidicineInfo数据");
    }


    @ApiOperation(value = "文字转语音", notes = "文字转语音")
    @PostMapping(value = "/textToAudio")
    public AjaxResult textToAudio( MedicineInfo medicineInfo, HttpServletRequest request , HttpServletResponse response) throws IOException {
        if (StringUtils.isNotBlank(medicineInfo.getAuditText())) {
            String audioUrl= getFileUrl(medicineInfo.getAuditText(),"",null);
            return success(audioUrl);
        }
        return success("");
    }

    @ApiOperation(value = "声音配置试听", notes = "声音配置试听")
    @GetMapping("/listeningTest")
    public AjaxResult listeningTest(DragSysConfig dragSysConfig) throws IOException {
            String audioUrl= getFileUrl(dragSysConfig.getListeningTest(),"",dragSysConfig);
            return success(audioUrl);
    }




    /**
     * 获取meidicineInfo详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(medicineInfoService.selectMedicineInfoById(id));
    }

    /**
     * 新增meidicineInfo
     */
    @Log(title = "meidicineInfo", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MedicineInfo medicineInfo) throws IOException {

        String tipMsg="";
        if(medicineInfo.getColorType()!=null){
            if(medicineInfo.getColorType()==1l){
                tipMsg="、活血祛瘀，通脉活络,";
            }
        }

        String allText=medicineInfo.getMedicineCnName()+",请仔细阅读说明书并在医师指导下使用";
        List<MedicineDetail> list=medicineInfo.getMedicineDetails();
        for(int i=0;i<list.size();i++){
            allText=allText+list.get(i).getTitle()+","+list.get(i).getContent()+","+tipMsg;
        }
        String voiceUrl=getFileUrl(allText+","+ tipMsg,"med"+medicineInfo.getId(),null);
        medicineInfo.setVoiceUrl(voiceUrl);
        return toAjax(medicineInfoService.insertMedicineInfo(medicineInfo));
    }

    @Log(title = "修改音色", businessType = BusinessType.INSERT)
    @PostMapping("/updateVoiceType")
    public AjaxResult updateVoiceType(@RequestBody MedicineInfo medicineInfo) throws IOException {
        DragSysConfig dragSysConfig= dragSysConfigService.selectDragSysConfigById(1l);
        medicineInfo.setVoiceType(dragSysConfig.getXfVoiceName());
        return toAjax(medicineInfoService.insertMedicineInfo(medicineInfo));
    }



    /**
     * 修改meidicineInfo
     */
    @Log(title = "修改药品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MedicineInfo medicineInfo) throws IOException {

        String tipMsg="";
        if(medicineInfo.getColorType()!=null){
            if(medicineInfo.getColorType()==1l){
                tipMsg="、活血祛瘀，通脉活络,";
            }
        }
        ///////////////
        String allText=medicineInfo.getMedicineCnName()+",请仔细阅读说明书并在医师指导下使用、"+tipMsg;
        List<MedicineDetail> list=medicineInfo.getMedicineDetails();
        for(int i=0;i<list.size();i++){
            allText=allText+list.get(i).getTitle()+","+list.get(i).getContent()+", ,";
        }
        String voiceUrl=getFileUrl(allText+","+tipMsg,"med"+medicineInfo.getId(),null);
        medicineInfo.setVoiceUrl(voiceUrl);
        return toAjax(medicineInfoService.updateMedicineInfo(medicineInfo));
    }

    // 同步最新颜音色；
    @Log(title = "修改音色", businessType = BusinessType.INSERT)
    @PostMapping("/freshVoiceType")
    @Transactional
    public AjaxResult freshVoiceType(@RequestBody MedicineInfo medicineInfo) throws IOException {

        System.out.println("======================同步音色===========================");
        MedicineInfo medicineInfo1=medicineInfoService.selectMedicineInfoById(medicineInfo.getId());
        String tipMsg="";
        if(medicineInfo1.getColorType()!=null){
            if(medicineInfo1.getColorType()==1l){
                tipMsg="、活血祛瘀，通脉活络,";
            }
        }

        List<MedicineDetail> list=medicineInfo1.getMedicineDetails();
        String allText=medicineInfo1.getMedicineCnName()+","+"请仔细阅读说明书并在医师指导下使用"+tipMsg+",";
        for(int i=0;i<list.size();i++){
            MedicineDetail medicineDetail=list.get(i);
            allText=allText+medicineDetail.getTitle()+","+medicineDetail.getContent()+",";
            //单独起线程u1
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
                     String voliceUrl= null;
//                    try {
                        voliceUrl = getFileUrl(medicineDetail.getTitle()+","+medicineDetail.getContent(),medicineDetail.getId()+"",null);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                        throw  new GlobalException("请稍后重试");
//                    }
                    medicineDetail.setVoiceUrl(voliceUrl);
                    medicineDetailService.updateMedicineDetail(medicineDetail);
//                }
//            }).start();
        }
        //同时生成总的播放音频；
        allText=allText+","+tipMsg;
        String allvoiceUrl= getFileUrl(allText,"med"+medicineInfo.getId(),null);
        medicineInfo1.setVoiceUrl(allvoiceUrl);
        return toAjax(medicineInfoService.updateOnlyMedicineInfo(medicineInfo1));
    }



    public   String   getFileUrl(String text,String id,DragSysConfig dragSysConfig) throws IOException {
        text =text.replaceAll( "Xuesaitong","血塞通");
        text =text.replaceAll( "Ruanjiaonang","软胶囊");
        text = text.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "").trim();
        // 将拼音转为英文

        //调用微服务接口获取音频base64
        String result = "";
        try {
            if(dragSysConfig==null){
                dragSysConfig= dragSysConfigService.selectDragSysConfigById(1l);
            }
            result = XunFeiUtil.convertText(text,dragSysConfig);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException("当前繁忙，请稍后重试");
        }
        //音频数据
        byte[] audioByte = Base64.getDecoder().decode(result);

        String filePath = RuoYiConfig.getUploadPath();
        filePath=filePath+"/"+"music"+"/"+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,new Date());
        File folder = new File(filePath);
        if (folder.exists() && folder.isDirectory()) {
        }
        else {
            folder.mkdirs();
            System.out.println("文件夹不存在");
        }
        //修改的时候；
        String  fileName=(new Date().getTime())+".mp3";
        if(StringUtils.isNotEmpty(id)){
            fileName=id+".mp3";
         }
        filePath=filePath+"/"+fileName;
        String fileUrl="music"+"/"+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,new Date())+"/"+fileName;
        // filePath = "D:\\project\\药品说明\\11.mp3";
        //  OutputStream os = new BufferedOutputStream(response.getOutputStream());
        FileOutputStream fos = new FileOutputStream(new File(filePath));
        try {
            System.out.println(audioByte);
            fos.write(audioByte);
            fos.close();
            return fileUrl;
            //音频流
            // os.write(audioByte);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fos.close();
            //os.flush();
            //  os.close();
        }
        return "";
    }


    @Log(title = "修改药品详情顺序", businessType = BusinessType.INSERT)
    @PostMapping("/updateMedicineDetialNumber")
    public AjaxResult updateMedicineDetialNumber(MedicineInfo medicineInfo){
        return AjaxResult.success(medicineInfoService.updateMedicineDetialNumber(medicineInfo));
    };



    /**
     * 删除meidicineInfo
     */
    @Log(title = "meidicineInfo", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(medicineInfoService.deleteMedicineInfoByIds(ids));
    }
}
